﻿using AppFlat.Application.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Newtonsoft.Json;
using System.Web;
using System.Data.Entity;
using AppFlat.Domain.Models;
using AppFlat.UI.WebApi.Filters;

namespace AppFlat.UI.WebApi.Controllers
{
    public class AppsController : ApiController
    {
        public IAppInfoService  AppService { get; set; }

        [AppAuthorize]
        public async Task<IHttpActionResult> GetList(int page = 1, int limit = 8, string key = "")
        {
            int total;
            var list = await AppService.GetEntities(page, limit, out total, a => a.Name.Contains(key), a => a.Id, false)
                .Select(n => new {Id=n.Id, Name=n.Name, CategoryName=n.Category.Name,DevUser=n.DevUser.Name })
                .ToListAsync();
            return Json(new { code = 0, msg = "", count = total, data = list });
           
        }

        public async Task<IHttpActionResult> Post([FromBody] AppInfo app)
        {
            app.DevUserId = 1;
            
            if (ModelState.IsValid)
            {
                var result = await AppService.AddAsync(app);
                return Ok("添加完成！");
            }
            return BadRequest("填写不正确！");
        }

        public async Task<IHttpActionResult> Put([FromBody] AppInfo app)
        {
            app.DevUserId = 1;

            if (ModelState.IsValid)
            {
                if(app.AppPath=="")
                {
                   // await AppService.UpdateAsync(app,"Name","CategoryId", "State", "Rom", "LastVersion","Remark");
                }
                else
                {
                    await AppService.UpdateAsync(app);
                }
                return Ok("修改完成！");
            }
            return BadRequest("填写不正确！");
        }

        public async Task<IHttpActionResult> GetById(int? id)
        {
            if (!id.HasValue)
                return BadRequest();
            var result = await AppService.GetEntityAsync(n => n.Id == id.Value);
            if (result == null)
                return NotFound();
            return Json(result);
        }

        [Route("api/upload")]
        public IHttpActionResult PostUpload()
        {
            var files = HttpContext.Current.Request.Files;  // 当前接受的文件集合
            if (files.Count>0)
            {
                var file = files[0];
                var name = Guid.NewGuid().ToString()+"."+file.FileName.Split('.')[1];
                file.SaveAs(HttpContext.Current.Server.MapPath("/uploads/" + name));

                return Json(new { code = 0, msg = "上传成功！", data = "http://localhost:8080/uploads/" + name });
            
            }
            return BadRequest("请选择上传文件");
        }

        public async Task<IHttpActionResult> Delete(int? id)
        {
            if (!id.HasValue)
                return BadRequest("请选择类别！");

            var result = await AppService.DeleteAsync(new AppInfo() { Id = id.Value, Name = "" });
            if (result)
                return Ok("删除完成！");

            return NotFound();
        }

        //批量删除
        public async Task<IHttpActionResult> DeleteByIds(int[] ids)
        {
            return Json(ids);
        }
    }
}
